import json

from django.forms import model_to_dict
from django.http import HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view

from account_sys.models import *
from utils.blank_utils import contains_false_val, contains_none
from utils.email_utils import valid_email
from utils.response_utils import *
from utils.session_utils import *

from enterprise_sys.models import Enterprise, Enterprise_Usr, Employee_info


# Create your views here.
@csrf_exempt
def register(request):
    if request.method != 'POST':
        return method_disallowed_response(request.method, 'POST')
    if has_login(request):
        user: User = get_login_user(request)
        return login_status_response(user.to_dict(), actual_login_status=True)

    data = json.loads(request.body)
    user_name = data.get('user_name')
    email = data.get('email')
    password = data.get('password')
    password_repeat = data.get('password_repeat')

    if contains_none(user_name, email, password):  # 不存在该键
        return format_error_response()

    if contains_false_val(user_name, email, password):  # 为空串
        return build_response(errno=2001, msg="user_name, email, password均不能为空")

    if not (2 <= len(user_name) <= 31) or valid_email(user_name):  # 不可以使用邮箱格式的用户名
        return build_response(errno=2002, msg="用户名不合法")

    if not (6 <= len(email) <= 63) or not valid_email(email):
        return build_response(errno=2003, msg="邮箱不合法")

    if not (4 <= len(password) <= 31):
        return build_response(errno=2004, msg="密码不合法")

    if password != password_repeat:
        return build_response(errno=2005, msg="两次输入的密码不一致")

    if User.objects.filter(name=user_name).exists():
        return build_response(errno=2006, msg="用户名已存在")

    if User.objects.filter(email=email).exists():
        return build_response(errno=2007, msg="邮箱已存在")

    User.objects.create(name=user_name, email=email, password=password)
    return build_response(msg="注册成功")


@csrf_exempt
def login(request):
    if request.method != 'POST':
        return method_disallowed_response(request.method, 'POST')

    if has_login(request):
        user = get_login_user(request)
        return login_status_response({
            "user": user.to_dict()
        }, actual_login_status=True)
    print("requestBody:")
    print(request.body)
    data = json.loads(request.body)
    account = data.get('account')  # 用户名或邮箱
    password = data.get('password')

    if contains_none(account, password):  # 不存在该键
        return format_error_response()

    if contains_false_val(account, password):  # 为空串
        return build_response(errno=2001, msg="account, password均不能为空")

    # 获取user对象和登录方式（user_name或email），获取失败则user置为None
    cur_login_method = "email" if valid_email(account) else "name"
    try:
        user = User.objects.get(**{cur_login_method: account})
    except User.DoesNotExist:
        user = None

    if user is None:
        return build_response(errno=2002, msg="账户不存在")

    if password != user.password:
        return build_response({
            "login_method": cur_login_method
        }, errno=2003, msg="密码错误")
    user_info = user.to_dict()
    firm_info = dict()
    query = Enterprise_Usr.objects.filter(usr=user)
    if query.count() == 0:
        firm_info['enterpriseId'] = None
        firm_info['enterpriseName'] = None
        firm_info['is_admin'] = False
    else:
        enterpriseId = query[0].enterprise_id
        enterprise_instance = Enterprise.objects.get(id=enterpriseId)
        firm_info['enterpriseId'] = enterpriseId
        firm_info['enterpriseName'] = enterprise_instance.name
        firm_info['is_admin'] = user.name == enterprise_instance.creator_name
    set_login_user(request, user)
    return build_response({
        "login_method": cur_login_method,
        "user": user_info,
        "enterprise": firm_info
    }, msg="登录成功")


@csrf_exempt
def logout(request):
    if request.method != 'POST':
        return method_disallowed_response(request.method, 'POST')

    if not has_login(request):
        return login_status_response()

    del_login_user(request)
    return build_response(msg="登出成功")


@csrf_exempt
def get_current_user(request):
    if request.method not in ['POST', 'GET']:
        return method_disallowed_response(request.method, 'POST', 'GET')

    if not has_login(request):
        return login_status_response()

    user = get_login_user(request)
    user_info = user.to_dict()
    firm_info = dict()
    query = Enterprise_Usr.objects.filter(usr=user)
    if query.count() == 0:
        firm_info['enterpriseId'] = None
        firm_info['enterpriseName'] = None
        firm_info['is_admin'] = False
    else:
        enterpriseId = query[0].enterprise_id
        enterprise_instance = Enterprise.objects.get(id=enterpriseId)
        firm_info['enterpriseId'] = enterpriseId
        firm_info['enterpriseName'] = enterprise_instance.name
        firm_info['is_admin'] = query[0].is_admin
    return build_response({
        "user": user_info,
        "enterprise": firm_info
    }, msg="获取成功")



@csrf_exempt
def get_info(request):
    if request.method != 'GET':
        return method_disallowed_response(request.method, 'GET')
    if not has_login(request):
        return build_response(errno=2001, msg='用户未登录')
    ID = request.GET.get('userID')
    user=User.objects.get(id=ID)
    if not user:
        return build_response(errno=58983, msg='用户不存在')
    message = user.info_to_dict()

    return build_response({
        "message": message
    },msg='获取成功')


@csrf_exempt
@api_view(['PUT'])
def update_user_info(request):
    if request.method != 'PUT':
        return method_disallowed_response(request.method, 'PUT')
    if has_login(request):
        user: User = get_login_user(request)
    else:
        return build_response(errno=2001, msg='用户未登录')
    firm_id = request.data.get('userID')
    if User.objects.filter(id=firm_id).count() == 0:
        return build_response(errno=58983, msg="用户不存在")
    firm = User.objects.get(id=firm_id)

    email = request.data.get('userEmail')
    sex = request.data.get('sex')
    height = request.data.get('height')
    phone = request.data.get('phone')
    education = request.data.get('education')
    school = request.data.get('school')
    address = request.data.get('address')
    skills = request.data.get('skills')
    text = request.data.get('text')
    intended_position = request.data.get('intended_position')

    if len(text) != 0 and len(text) > 1024:
        return build_response(errno=58983, msg='简介过长1024')

    firm.text = text
    firm.sex = sex
    firm.email = email
    firm.height = height
    firm.phone = phone
    firm.education = education
    firm.school = school
    firm.address = address
    firm.skills = skills
    firm.intended_position = intended_position
    firm.save()
    other_info = {"success": True}
    return build_response(other_info=other_info, errno=1, msg='修改成功')

@csrf_exempt
def get_Employee_info(request):
    if request.method != 'GET':
        return method_disallowed_response(request.method, 'GET')
    if not has_login(request):
        return build_response(errno=2001, msg='用户未登录')
    ID = request.GET.get('userID')
    enterprise_usr=Enterprise_Usr.objects.filter(usr_id=ID)
    if enterprise_usr.count() == 0:
        return build_response(errno=58983, msg='当前用户未加入企业')
    e_u=enterprise_usr[0].id
    e_id = enterprise_usr[0].enterprise_id
    #print(e_u)
    employee_info=Employee_info.objects.get(e_u_id=e_u)
    enterprise_name = Enterprise.objects.get(id=e_id)

    return build_response({
        "enterprise":enterprise_name.name,
        "position":employee_info.position
    },msg='获取成功')


@csrf_exempt
def searchUser(request):
    if request.method != 'GET':
        return method_disallowed_response(request.method, 'GET')
    if not has_login(request):
        return build_response(errno=2001, msg='用户未登录')
    username = request.GET.get('userName')
    users =  User.objects.filter(name__icontains=username)
    if users.count() == 0:
        return build_response(msg='不存在该用户', other_info={"success": False})
    data = []
    for user in users :
        user1 = model_to_dict(user)
        in_enterprise = True
        e_u = Enterprise_Usr.objects.filter(usr_id=user.id)
        if e_u.count() == 0:
            in_enterprise = False
            user1['in_enterprise'] = in_enterprise

        else:
            employee_info = Employee_info.objects.filter(e_u_id=e_u[0].id)
            print(e_u[0].id)
            enterprise = Enterprise.objects.filter(id=e_u[0].enterprise_id)
            user1['in_enterprise'] = in_enterprise
            user1['enterprise_id'] = enterprise[0].id
            user1['enterprise_name'] = enterprise[0].name
            user1['enterprise_position'] = employee_info[0].position  # 如果需要添加职位信息
            user1['is_admin'] = e_u[0].is_admin
        data.append(user1)

    #print(data)
    return build_response({
        "success":True,
        "datalist":data
    })





